package com.plugin.view

import android.content.Context
import android.view.View
import com.map.interfaces.OnMapLoadComplete
import com.map.tiandimap.MapView
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.platform.PlatformView

/**
 * Create： zhangjunfei 4/14/21 10:52 AM
 * 描述：天地图地图插件
 */
class TianDiMapView(
    context: Context,
    viewId: Int,
    params: HashMap<*, *>,
    messenger: BinaryMessenger
) : PlatformView, MethodCallHandler {
    private val mapView: MapView = MapView(context)

    /**
     * view的标志
     */
    private val sign = "mapView"

    /**
     * 与flutter通信信道
     */
    private val methodChannel: MethodChannel = MethodChannel(messenger, "${sign}_${viewId}")

    /**
     * 地图控制类,默认15级别
     */
    private val mapViewControl: MapViewControl =
        MapViewControl(mapView, params["zoomLevel"] as Int)

    /**
     * 当前展示的地图中心的坐标
     */
    private val center = params["center"] as Map<*, *>

    init {
        methodChannel.setMethodCallHandler(this)
        mapView.setOnMapLoadListener(onMapLoadComplete = object : OnMapLoadComplete {
            override fun onComplete() {
                //设置地图的中心点
                mapView.setCenter(
                    lng = center["lng"]!! as Double,
                    lat = center["lat"]!! as Double,
                    zoom = 15
                )
                //通知flutter地图已加载完成
                methodChannel.invokeMethod("mapCompleted", null)
            }
        })
    }

    override fun getView(): View {
        return mapView
    }

    override fun dispose() {
        mapView.destroy()
    }

    override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
        when (call.method) {
            "showLocation" -> mapViewControl.showLocation(result)
            "setMapCenter" -> mapViewControl.setMapCenter(call, result)
            "zoomToLevel" -> mapViewControl.zoomToLevel(call, result)
            "addInfoWindow" -> mapViewControl.addInfoWindow(call, result)
            "addOnPolygonClickListener" -> mapViewControl.addOnPolygonClickListener(
                methodChannel,
                result
            )
            "addOnInfoWindowClickListener" -> mapViewControl.addOnInfoWindowClickListener(
                methodChannel,
                result
            )
            "addMarker" -> {
            }
            "addMarkers" -> {
            }
            "clearMarkers" -> mapViewControl.clearMarkers(result)
            "addArea" -> mapViewControl.addArea(call, result)
            "clearAreas" -> mapViewControl.clearAreas(result)
        }
    }
}